package com.yinet.web.controller.yctk;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.yinet.common.annotation.Log;
import com.yinet.common.config.Global;
import com.yinet.common.config.ServerConfig;
import com.yinet.common.core.controller.BaseController;
import com.yinet.common.core.domain.AjaxResult;
import com.yinet.common.core.domain.Ztree;
import com.yinet.common.core.page.TableDataInfo;
import com.yinet.common.json.JSON;
import com.yinet.common.utils.DateUtils;
import com.yinet.common.utils.StringUtils;
import com.yinet.common.utils.file.FileUploadUtils;
import com.yinet.common.utils.http.HttpUtils;
import com.yinet.framework.util.ShiroUtils;
import com.yinet.generator.domain.YinetNotPass;
import com.yinet.generator.domain.YinetVideo;
import com.yinet.generator.domain.YinetYctk;
import com.yinet.system.domain.CheckTable;
import com.yinet.system.domain.YctkData;
import com.yinet.system.service.CheckTableService;
import com.yinet.system.service.impl.YctkDataService;
import com.yinet.system.service.impl.YctkTypeService;
import com.yinet.web.controller.tool.json.JsonResourceUtils;
import com.yinet.web.utils.allocation;
import com.yinet.yyqh.service.Yctkervice;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 远程探勘列表Controller
 *
 * @author yinet
 * @date 2019-09-02
 */
@Controller
@RequestMapping("/Rong")
public class LongRangeController extends BaseController {

    private String prefix = "yctk/";
    @Autowired
    private Yctkervice yctkService;

    @Autowired
    private YctkTypeService yctkTypeService;

    @Autowired
    private CheckTableService checkTableService;

    @Autowired
    private YctkDataService yctkDataService;

    @Autowired
    private ServerConfig serverConfig;

    /**
     * 获取审批表单集合
     * @return
     */
    @PostMapping("/tcTableList")
    @ResponseBody
    public AjaxResult tcTableList(){
        return AjaxResult.success(yctkTypeService.selectTableNameList());
    }


    /**
     * 获取审批表单详情
     * @return
     */
    @PostMapping("/tcTableInfo")
    @ResponseBody
    public AjaxResult tcTableInfo(int id){
        List<YctkData> l = yctkDataService.selectByFTableIdList(id);
        for (YctkData yd : l){
            yd.setData(yctkDataService.selectByTableIdList(yd.getId()));
        }
        return AjaxResult.success(l);
    }

    /**
     * 暂存整改
     * @return
     */
    @Log(title = "暂存表单")
    @PostMapping("/saveCheck")
    @ResponseBody
    public AjaxResult saveCheck(String json,String ud){
        List<CheckTable> cts =  JSONObject.parseArray(json,CheckTable.class);
        List<CheckTable> list = checkTableService.selectByOID(ud);
        System.err.println(list.size());
        if(list.size()>0){
            List<CheckTable> nl = new ArrayList<>();
            for (CheckTable ct : cts){
                nl.addAll(ct.getData());
            }
            int index = 0;
            for (int i = 0; i < list.size(); i++){
                if(list.get(i).getRowContent() != null){
                    list.get(i).setRowResult(nl.get(index).getRowResult());
                    System.err.println(nl.get(index).getRowResult());
                    list.get(i).setUpdateTime(DateUtils.getNowDate());
                    index++;
                }

            }
            checkTableService.updateList(list);
        }else{
            String uuid = UUID.randomUUID().toString();
            for (CheckTable ct : cts){
                ct.setUuid(uuid);
                ct.setCreateBy(ShiroUtils.getLoginName());
                ct.setCreateTime(DateUtils.getNowDate());
                ct.setUpdateTime(DateUtils.getNowDate());
                checkTableService.insert(ct);
                for (CheckTable checkTable : ct.getData()){
                    checkTable.setCreateBy(ShiroUtils.getLoginName());
                    checkTable.setCreateTime(DateUtils.getNowDate());
                    checkTable.setUpdateTime(DateUtils.getNowDate());
                    checkTable.setParentId(ct.getId());
                    checkTable.setUuid(uuid);
                }
                checkTableService.insertList(ct.getData());
            }
        }
        return AjaxResult.success();
    }

    /**
     * 查询暂存表单
     * @return
     */
    @Log(title = "查询暂存表单")
    @PostMapping("/selectIsFirst")
    @ResponseBody
    public AjaxResult selectIsFirst(String uuid){
        return AjaxResult.success(checkTableService.selectByOID(uuid));
    }
    //未踏勘
    @GetMapping("/prospectUnfin")
    public String prospectUnfin(Model model ) {
        model.addAttribute("user",ShiroUtils.getLoginName());
        model.addAttribute("yctk", 0);
        return prefix + "unfinished";
    }
    //整改中
    @GetMapping("/accomplish")
    public String entSet(Model mmp) {
        mmp.addAttribute("yctk", 1);
        return prefix + "unfinished";
    }
    //已办
    @GetMapping("/noPass")
    public String noPass(Model mmp) {
        mmp.addAttribute("yctk", 2);
        return prefix + "unfinished";
    }
    //踏勘
    @GetMapping("/export/{id}")
    public String export(@PathVariable("id") String id,Model model) {
        //id查询信息
        YinetYctk yctk=yctkService.selectById(id);
        model.addAttribute("user",ShiroUtils.getLoginName());
        model.addAttribute("uuid",yctk.getUuid());
        model.addAttribute("sfzCard",yctk.getSfzcard());
        model.addAttribute("username",yctk.getUsername());
        model.addAttribute("phone",yctk.getPhone());
        model.addAttribute("qyAddress",yctk.getQyAddress());
        model.addAttribute("makeTime",yctk.getMakedate());
        model.addAttribute("date",new Date());
        System.err.println("踏勘时间："+yctk.getMakedate());
        model.addAttribute("qyName",yctk.getQyName());
        //查询当前id的账号isfinish信息
        List<YinetYctk>list=yctkService.selectIsfinishCard(id);
        boolean flg=true;
        for (YinetYctk yinetYctk:list){
            if (yinetYctk.getIsfinish().equals("3")){
                model.addAttribute("isfinish",yinetYctk.getIsfinish());
                flg=false;
            }
        }
        if(flg){
            model.addAttribute("isfinish","0");
        }
        return prefix + "starindex";
    }
    /**
     * 远程踏勘列表
     */
    @PostMapping("/list/{isfinish}")
    @ResponseBody
    public TableDataInfo genList(@PathVariable("isfinish") String isfinish,YinetYctk yctk)
    {

        System.err.println("isfinish:"+isfinish);
        String login=ShiroUtils.getLoginName();
        startPage();
        List<YinetYctk> list = yctkService.selectYinetYctk(isfinish,yctk,login);
        return getDataTable(list);
    }
    //添加踏勘
    @GetMapping("/add")
    public String add(Model model) {
        model.addAttribute("change",true);
        model.addAttribute("login",false);
        return prefix + "add";
    }
    //添加踏勘
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(YinetYctk yinetYctk) {
        System.err.println("添加："+yinetYctk);
        yinetYctk.setAdd_Time(new Date());
        yinetYctk.setLoginName(ShiroUtils.getLoginName());
        yinetYctk.setUuid(UUID.randomUUID().toString());
//        String s=sendMessage("付宇航","15612104624", "1", "1");
//       System.err.println("s:"+s);

        return toAjax(yctkService.insertYctk(yinetYctk));
    }

    //查找人员
    @GetMapping("/person")
    public String selectPerson() {
        return prefix + "person";
    }

    //查找人员
    @GetMapping("/personList")
    @ResponseBody
    public List<Ztree> personlist() {
        //查找人员
        List<Ztree> ztrees = yctkService.selectUserName();
        return ztrees;
    }


    //删除踏勘
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        System.err.println("删除:"+ids);
        return toAjax(yctkService.deleteYctk(ids));
    }
    //重置状态
    @PostMapping("/reset")
    @ResponseBody
    public AjaxResult reset(String id) {
        return toAjax(yctkService.updateReset(id));
    }


    //查询踏勘地址
    @PostMapping("/site")
    @ResponseBody
    public AjaxResult site(@RequestParam("uuid")String uuid) {
        System.err.println("查询地址:"+uuid);
        //修改uuid为正在踏勘中
    //        yctkService.updateIsfinish(uuid);
        //查询踏勘地址
        YinetYctk yctk=yctkService.selectSite(uuid);
        System.err.println("查询地址:"+yctk);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("site", yctk.getYc_site());
        ajax.put("QyName", yctk.getQyName());
        ajax.put("name", yctk.getUsername());
        ajax.put("x", yctk.getYcSiteX());
        ajax.put("y", yctk.getYcSiteY());
        return ajax;
    }
    //查询踏勘状态
    @PostMapping("/isfinish")
    @ResponseBody
    public AjaxResult isfinish(@RequestParam("id")String id) {
        YinetYctk yctk=yctkService.selectById(id);
        System.err.println("查询踏勘状态:"+yctk);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("state",yctk.getState());
        return ajax;
    }

    @PostMapping("/video")
    @ResponseBody
    public AjaxResult uoloadVideo(@RequestParam("file") MultipartFile file,@RequestParam("id") String id) throws Exception {
        try {
            System.err.println("id:"+id);
            // 上传文件路径
            String filePath = Global.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("fileName", fileName);
            ajax.put("url", url);
            //添加视频
            YinetVideo video=new YinetVideo();
            video.setUuid(id);
            video.setVideo(fileName);
            video.setData(new Date());
            int i=yctkService.insertVideo(video);
            return ajax;
        } catch (Exception e) {
            System.err.println(e.getMessage());
            return AjaxResult.error(e.getMessage());
        }
    }

   //修改
    @GetMapping("edit/{Id}")  //项目id
    public String edit(@PathVariable("Id") String id, Model model) {
        YinetYctk yctk=yctkService.selectById(id);
        boolean login=true;
        if(yctk.getLoginName().equals(ShiroUtils.getLoginName())){
            login=false;
        }
        if(ShiroUtils.getLoginName().equals(allocation.getShopWx())){
            login=false;
        }
        model.addAttribute("login",login);
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String strDate=sdf.format(yctk.getMakedate());
        model.addAttribute("yctk",yctk);
        model.addAttribute("strDate",strDate);
        model.addAttribute("change",false);
        return prefix + "add";
    }
    /**
     * 修改保存
     */
    @PostMapping("/upedit/{Id}")
    @ResponseBody
    public AjaxResult upedit(@PathVariable("Id") String id, YinetYctk yctk) {
        yctk.setLoginName(ShiroUtils.getLoginName());
        yctk.setId(Integer.parseInt(id));
        return toAjax(yctkService.updateYctk(yctk));
    }

    @PostMapping("/columnList")
    @ResponseBody
    public AjaxResult columnList(@RequestParam("date")String date) {

        System.err.println("date:"+date);
        String json = JsonResourceUtils.getJsonObjFromResource("/config.properties.json");
//        JSONObject jo = JSONObject.parseObject(new String(json));
//        json=json.substring(1);
//        json=json.substring(0,json.length()-1);
        System.err.println("json:"+json);
        Gson gson=new Gson();
        JSONObject jo = JSONObject.parseObject(json);
        System.err.println(jo);
        Map<String,Object> map=new HashMap<>();
        return null;
    }

    /**
     * 踏勘通过
     */
    @PostMapping("/export/Rong/tongguo/{uuid}")
    @ResponseBody
    public AjaxResult tongguo(@PathVariable("uuid") String uuid) {
        System.err.println("踏勘通过:"+uuid);
        return toAjax(yctkService.updateTaKanTG(uuid));
    }

    /**
     * 踏勘不通过
     */
    @PostMapping("/export/Rong/butongguo/{uuid}")
    @ResponseBody
    public AjaxResult butongguo(@PathVariable("uuid") String uuid,String reason) {
        //踏勘不通过
        yctkService.updateBTG(uuid);
        YinetNotPass pass=new YinetNotPass();
        pass.setUuid(uuid);
        pass.setReason(reason);
        pass.setAddtime(new Date());
        //添加不通过
        int i=yctkService.addNotPass(pass);
        System.err.println("踏勘不通过:"+uuid);
        System.err.println("踏勘不通过理由:"+reason);
        return toAjax(i);
    }


        /**
         * 打开地图
         * @param x 经度
         * @param y 纬度
         * @param address 地址
         * @return
         */
        @GetMapping("/openMaps")
        public String openMaps(String x, String y, String address, Model m){
            m.addAttribute("x",x);
            m.addAttribute("y",y);
            m.addAttribute("address",address);
            return prefix + "tcmaps";
        }


    private String sendMessage(String name,String phone,String gtname,String sendback) {
        String info = null;
        String result ="";
        try {
            String url = "http://api.sms.cn/sms/";
            String parme = "";
            if (sendback != null) {
                parme = "ac=send&uid=qxspj&pwd=8d18d2eb316841db0998eeb67362ba4c&mobile=" + phone
                        + "&content=" + name + "您好:您申请的个体工商户《" + gtname + "》审核未通过。原因:" + sendback + "【藁城区行政审批局】";
            } else {
                parme = "ac=send&uid=qxspj&pwd=8d18d2eb316841db0998eeb67362ba4c&mobile="
                        + phone + "&content=" + name + "您好:您申请的个体工商户《" + gtname + "》审核通过,请及时打印营业执照【藁城区行政审批局】";
            }
             result = HttpUtils.sendGet(url, parme);
        }catch (Exception e) {
            e.printStackTrace();
            System.err.println(e.getMessage());
        }
//
//            HttpClient httpclient = new HttpClient();
//            PostMethod post = new PostMethod("http://api.ums86.com:8899/sms/Api/Send.do");//
//            post.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "gbk");
//            post.addParameter("SpCode", "247007");
//            post.addParameter("LoginName", "jxxzspj");
//            post.addParameter("Password", "kqxzspj147");
//            if(sendback==null) {
//                post.addParameter("MessageContent", name + "您好:您申请的个体工商户《" + gtname + "》审核通过,请及时打印营业执照。");
//                post.addParameter("UserNumber", phone);
//                post.addParameter("SerialNumber", "");
//                post.addParameter("ScheduleTime", "");
//                post.addParameter("f", "1");
//            }else{
//                post.addParameter("MessageContent", name + "您好:您申请的个体工商户《" + gtname + "》审核未通过,原因："+sendback);
//                post.addParameter("UserNumber", phone);
//                post.addParameter("SerialNumber", "");
//                post.addParameter("ScheduleTime", "");
//                post.addParameter("f", "1");
//            }
//            httpclient.executeMethod(post);
//            info = new String(post.getResponseBody(),"gbk");
//            System.out.println(info);
//
//        }catch (Exception e) {
//            e.printStackTrace();
//        }
        return result;
    }
}
